// pages/draw/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 2,
    logo: '',
    logotemp: '',
    picname: '',
    pictemp: '',
    coverInfo: {},
    title: '是时候与懒癌宣战了，来挑战一下自己！',
    window: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.id = options.id ? options.id : 83640;
    var userinfo = wx.getStorageSync('user_info');
    var window = wx.getSystemInfoSync();
    var boxHeight = window.windowHeight - 50;
    var boxWidth = window.windowWidth-20;
    boxWidth = boxWidth > window.windowWidth ? window.windowWidth : boxWidth;
    this.setData({ userinfo: userinfo, window: window, boxWidth: boxWidth, boxHeight: boxHeight, imageCoverWidth: boxWidth - 30, icoWidth: boxWidth * 0.2, textareaWidth: boxWidth * 0.65 });
    this.getLogo();
    this.getTopic();
   // this.formSubmit();
  },

  getLogo: function () {
    var that = this;
    app.api('user/getLogo', {
      id: that.data.id
    }, function (res) {
      //wx.stopPullDownRefresh();
      if (res.code != 200) {
        app.alert(res.msg);
        return false;
      }
      that.setData({ logo: res.data });
      that.downloadFile(res.data);
    })
  },
  getTopic: function () {
    var that = this;
    app.api('topic/detail', {
      fields: "user,id,title,user_id,user,user_join,topic_join.days,user_count,topic_join.rank,cover",
      id: that.data.id
    }, function (res) {
      //wx.stopPullDownRefresh();
      if (res.code != 200) {
        app.alert(res.msg);
        return false;
      }
      // var title = that.data.userinfo.nickname + '邀请你参与"' + res.data.title+'"'
      //  console.log(res.data);
      that.downloadFile(res.data.cover, 'pictemp');
      that.setData({ data: res.data, picname: res.data.cover });
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  cutText: function (text) {
    var shareText = [];
    var word = 16;
    var max = text.length;
    var tmptext = "";
    var count = 1;
    for (var i in text) {
      tmptext += text[i];
      if (count == word) {
        shareText.push(tmptext);
        tmptext = "";
        count = 0;
      }
      count++;
    }
    //console.log("cou",count,'max',max);
    if (count < max + 2) {
      shareText.push(tmptext);
    }
    console.log(shareText);
    return shareText;
  },

 

  draw: function () {
   // var postData = e.detail.value;
   
    
    if (this.data.logotemp=='' || this.data.pictemp==''){
      return ;
    }

    var text = "一天打一次卡呀";
   // this.setData({ type: 2 });
    var shareText = this.cutText(text);
    // console.log(text);
    //console.log(shareText);
    // var shareText = [];
    // shareText[0] = '“我好啊！位置都会变。';
    // shareText[1] = "不知道还有没有其他方法让他居中显示”";
    var logo = this.data.logotemp;
    // var logo = '/image/gh_87bdb895ea90_430.jpg';
    var cover = this.data.pictemp;
    const ctx = wx.createCanvasContext('myCanvas');
    //背景色
    var imgBoxW = this.data.boxWidth ;
    var imgBoxH = this.data.boxHeight - 60;
    ctx.setFillStyle('#ffffff');
    ctx.fillRect(0, 0, imgBoxW, imgBoxH);
    this.data.imgBoxW = imgBoxW;
    this.data.imgBoxH = imgBoxH;
    //图片层
    // var imgBoxW = this.data.boxWidth - 20;
    // var imgBoxH = this.data.boxHeight - 90;
    // ctx.setFillStyle('#ffffff');
    // ctx.fillRect(10, 80, imgBoxW, imgBoxH);
    //标题
    // ctx.setTextAlign('center');
    // ctx.setFontSize(18);
    // ctx.fillText(this.data.title, this.data.boxWidth*0.5, 50);
    //封面
    var coverInfo = this.data.coverInfo;
    var imageCoverH = imgBoxH * 0.6;
    //高图片
    var imageCoverWidth = (imageCoverH / coverInfo.height) * coverInfo.width;
    //图片居中 
    var left = (imgBoxW - imageCoverWidth) / 2;
    ctx.drawImage(cover, left, 0, imageCoverWidth, imageCoverH);
    //用户名
    var top =   40;
    ctx.setFillStyle('#ffffff')
    ctx.setFontSize(18);
    ctx.setTextAlign('center');
    ctx.fillText(this.data.data.user.nickname, imgBoxW * 0.5, top );
    //我在计划猫坚持打卡，立志做一个自律的人
    ctx.setFontSize(15);
    ctx.setTextAlign('center');
    ctx.fillText("“"+this.data.data.title+"”", imgBoxW * 0.5, top+35);
    //打卡天数
    var fontTop = top+75;
    ctx.setFontSize(12);
    ctx.setTextAlign('center');
    ctx.fillText("打卡天数", imgBoxW * 0.5 - 60, fontTop);
    var day = this.data.data.days;
    ctx.setFontSize(40);
    ctx.setTextAlign('center');
    ctx.fillText(day, imgBoxW * 0.5 - 60, fontTop + 50);

    ctx.setFontSize(12);
    ctx.setTextAlign('left');
    if (day>9){
      var left = imgBoxW * 0.5 - 60 + 30;
    }else{
      var left = imgBoxW * 0.5 - 60 + 20;
    }
    ctx.fillText("天", left, fontTop + 50);
    //分割线
    ctx.moveTo(imgBoxW * 0.5, fontTop)
    ctx.lineTo(imgBoxW * 0.5, fontTop + 50);
    ctx.setStrokeStyle('#ffffff')
    ctx.stroke()
    //打卡排名
    var rank = this.data.data.rank;
    ctx.setFontSize(12);
    ctx.setTextAlign('center');
    ctx.fillText("排名", imgBoxW * 0.5 + 60, fontTop);
    ctx.setFontSize(40);
    ctx.setTextAlign('center');
    ctx.fillText(rank, imgBoxW * 0.5 + 60, fontTop + 50);
    //小目标文字
    // var top = imageCoverH + 40;
    // ctx.setFillStyle('#444444')
    // ctx.setFontSize(16);
    // ctx.setTextAlign('center');
    // var step = 0;
    // for (var i in shareText) {
    //   step = i * 16 * 1.5;
    //   ctx.fillText(shareText[i], imgBoxW * 0.5, top + step);
    // }
    //二维码
    var imageCoverWidth = imgBoxW * 0.2;
    var top = imgBoxH - imageCoverWidth - imageCoverWidth * 0.5 - 35;
    var left = imgBoxW * 0.4;
    ctx.drawImage(logo, left, top, imageCoverWidth, imageCoverWidth);

    //版权
    var top = imgBoxH - 20;
    ctx.setFillStyle('#666666')
    ctx.setFontSize(12);
    ctx.setTextAlign('center');
    ctx.fillText("@计划猫，立志做一个自律的人", imgBoxW * 0.5, top);
    ctx.draw()



  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  canle: function () {
    this.setData({ type: 1 });
  },
  navigateBack: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  canvasSave: function () {
    wx.showToast({
      title: '正在生成图片...',
      icon: 'loading',
      duration: 5000
    });
    var destWidth = 1200;  
    var destHeight = (destWidth / this.data.imgBoxW) * this.data.imgBoxH ;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      fileType:'png',
      // width: 50,
      // height: 50,
      // destWidth: 100,
      destHeight: destHeight,
      destWidth: destWidth,
      canvasId: 'myCanvas',
      fail: function (res) {
        console.log(res);
      },
      success: function (res) {
        console.log(res.tempFilePath)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            app.alert("图片保存成功，可到相册查看");
            // wx.previewImage({
            //   urls: [res.tempFilePath],
            // })
          },
          fail: function (res) {
            //console.log(res);
            app.alert(res.errMsg);
          },
          complete: function () {
            wx.hideToast();
          }
        })
      }
    })
  },
  downloadFile: function (url, type = "logotemp") {
    var that = this;
    wx.downloadFile({
      url: url,
      complete: function () {
        wx.hideToast();
         
      },
      fail: function (res) {
        app.alert(res.errMsg);
      },
      success: function (res) {
        wx.hideToast();
        if (res.statusCode === 200) {
          if (type == "logotemp") {
            that.data.logotemp = res.tempFilePath;
            that.draw();
          } else {
            that.data.pictemp = res.tempFilePath;
            wx.getImageInfo({
              src: res.tempFilePath,
              success: function (res) {
                that.setData({ coverInfo: res });
                that.draw();
              }
            })
          }
        } else {
          app.alert(res.errMsg);
          console.log(res);
        }
      }
    })


  }

})